<template>
  <!-- 弹窗遮罩层 -->
  <div v-if="showWinDialog" >
    <div class="win-dialog">
      <h2>🎉 你赢了！ 🎉</h2>
      <button @click="closeDialog">关闭</button>
    </div>
  </div>
    <div :class="['full-screen-border1',{'blur-background': showWinDialog}]">
      <div class="top">
        <LandPai  v-for="(item,index) in landlordCards" :key="index" :landlordCard="item" :landlordCardlog="landlordCardlog2"/>
      </div>
      <div class="miden">

        <div class="left">
          <Paib v-show="true" v-for="(item,index) in pais" :key="index" :pai="item"/>
        </div>
        <div class="content">

     

          <div class="shoupai1">
            <Pai  v-for="(item,index) in leftContainer" 
            :key="index" 
            :pai="item" />

          </div>

          <div class="shoupai2">
            <Pai  v-for="(item,index) in rightContainer" 
            :key="index" 
            :pai="item" />
 
          </div>
          <!-- 出牌区 -->
          <div class="chupai">
            <Pai  v-for="(item,index) in selectedCard" 
            :key="index" 
            :pai="item" />
          </div>
          <div v-if="!imgshow && !landlordCardlog2"  class="image-wrapper">
            <img src="/src/assets/bouton.png" alt="Button" class="btn-image"/>
            <!-- 文字层 -->
            <div  class="art-text" @click="callLand">叫地主</div>
                <!-- 禁用遮罩层 -->
            <div 
            v-show="!landlordCardlog" 
            class="disable-overlay"
            ></div>
          </div>

          <div v-if="landlordCardlog2"  class="image-wrapper">
            <img src="/src/assets/bouton.png" alt="Button" class="btn-image"/>
            <!-- 文字层 -->
            <div  class="art-text" @click="playcard">出牌</div>
                <!-- 禁用遮罩层 -->
            <div 
            v-show="!playlog" 
            class="disable-overlay"
            ></div>
          </div>


          <div v-if="!imgshow && !landlordCardlog2"  class="image-wrapper2">
            <img src="/src/assets/bouton.png" alt="Button" class="btn-image"/>
            <!-- 文字层 -->
            <div class="art-text" @click="passland">不叫</div>
                <!-- 禁用遮罩层 -->
                <div 
                v-show="!landlordCardlog" 
                class="disable-overlay"
                ></div>            
          </div>

          <div v-if="landlordCardlog2"  class="image-wrapper2">
            <img src="/src/assets/bouton.png" alt="Button" class="btn-image"/>
            <!-- 文字层 -->
            <div class="art-text" @click="passcard">不出</div>
                <!-- 禁用遮罩层 -->
                <div 
                v-show="!playlog" 
                class="disable-overlay"
                ></div>            
          </div>
          
          <img 
          v-show="imgshow"
          :src="imageUrl"
          :style="imageStyle"
          ref="imageRef"
          v-on:click="fetchGameState"  
          >

        </div>
          <div class="right">
            <Paib2 v-show="true" v-for="(item,index) in pais" :key="index" :pai="item"/>
          </div>   
      </div>
      <div class="down">
          <Pai  v-for="item in pais" 
          :key="item.uniqueId" 
          :pai="item"
          :is-selected="selectedCard.some(c => c.uniqueId === item.uniqueId)" 
          @play-card="handleCardPlayed"  />
      </div>
      <!-- <div class="down">
        <Pai  v-for="(item,index) in pais" 
        :key="index" 
        :pai="item"
        @play-card="handleCardPlayed"  />
    </div> -->
    </div>
  
  
  </template>
  
  <script setup>
  import Pai from '@/components/game/pai.vue'
  import Paib from '@/components/game/paib.vue';
  import Paib2 from '../../components/game/paib2.vue';
  import LandPai from '@/components/game/landPai.vue';
  import { ref, onMounted } from 'vue'
  import axios from 'axios';
  import { useUserStore } from '@/store/userstore'
import { ElMessage } from 'element-plus';
import { validateCardType } from '@/utils/cardUtils';
import { sortCards } from '@/utils/cardUtils';
import { getNextPlayerId, generateUniqueId } from '@/utils/common'
import { canBeat } from '@/utils/cardComparison'
import { useGameActions } from '@/composables/useGameActions';
import { useGameState } from '@/composables/useGameState';
import { 
  initWebSocketMessenger, 
  sendGameMessage,
  sendMessage
} from '@/services/webSocketMessenger';


const userStore = useUserStore()
console.log(userStore.username) // 输出: JohnDoe
console.log(userStore.id) // 输出: JohnDoe

// 图片地址
const imageUrl = ref('src/assets/statelog.png');
// const Room = ref(null)

const imgshow = ref(true)
const showWinDialog=ref(false)
// const landlordCards =ref([])
const landlordCardlog =ref(false)
const landlordCardlog2 =ref(false)


// // const pais = ref([])
// const player=ref(null)
// player.name=userStore.username
// player.id=userStore.id
// player.score=0
 const playlog=ref(false)


// 玩家信息
const player = ref({
  name: userStore.username,
  id: userStore.id,
  score: 0,
  sx: 0,
  bid: false
});
// // 当前选择的卡牌
// const selectedCard = ref([]);
// // 选中牌状态管理
// const selectedCards = ref([])
// //上一手牌
// const upCard=ref([])
// //左边牌
// const leftContainer=ref([])
// //右边牌
// const rightContainer=ref([])

// 游戏状态和逻辑
let ws ;
const imageStyle = ref({
  position: 'absolute',
  wwidth: '20%',       // 固定宽度
  height: '20%',       // 自动高度保持比例
  left: '50%',          // 水平居中
  top: '70%',           // 垂直居中
  transform: 'translate(-50%, -50%)', // 居中微调
  objectFit: 'cover' ,   // 保持比例填充容器
});
//游戏状态
const gameState = useGameState();
const { Room, pais, selectedCard, upCard, leftContainer, rightContainer, landlordCards } = gameState;

// 游戏动作
const gameActions = useGameActions(player, gameState);
const { handleCardPlayed, playCard, passCard, callLandlord, passLandlord } = gameActions;

// UI动作处理
const callLand = () => {
  if (!landlordCardlog.value) return;
  landlordCardlog.value = false;
  callLandlord(player.value.score, sendGameMessage);
};
const playcard=()=>{
  if(playlog.value==false)return
    playlog.value=false
    if(!playCard(sendGameMessage,showWinDialog)){
      playlog.value=true
    }
}
const passcard=()=>{
  if(playlog.value==false)return
  playlog.value=false

  passCard(sendGameMessage)
}
const passland=()=>{
  if (!landlordCardlog.value) return;
  landlordCardlog.value = false;
  passLandlord(sendGameMessage)
}


const fetchGameState = async () => {
  imgshow.value =false
  sendMessage("creatroom",
  { player: player.value.name,
    id:player.value.id})

}
// 3. 处理创建房间结果
function handleCreateRoomResult(data) {
  if (data) {
    console.log("房间创建成功，ID:", data);
    // 更新 UI 或存储房间 ID
  } else {
    console.error("创建房间失败:", data.error);
  }
}

// 3. 处理创建房间结果
function handleStartGameResult(data) {
  if (data) {
    console.log("房间加入成功，ID:", data);
    // 更新 UI 或存储房间 ID
  } else {
    console.error("创建加入失败:", data.error);
  }
}
// 3. 处理人数不够
function handleStarterroeResult(data) {
  if (data) {
    console.log("人数不够:", data);
    // 更新 UI 或存储房间 ID
  } else {
    console.error("创建加入失败:", data.error);
  }
}




// 3. 初始化手牌
function initsResult(data) {
  if (data) {
    const room = JSON.parse(data); // 解析 room 数据
    Room.value=room;
    console.log(Room.value)
    let j=0;
    for (let i = 0; i < 3; i++) {
      if (room.players[i].name === player.value.name) {
      // 修改后（确保全局唯一）
      pais.value = sortCards(room.players[i].handCards.map((card, index) => ({
        ...card,
      uniqueId: generateUniqueId(card, player.value.name, index) // 结合玩家索引和时间戳
      })));
      landlordCards.value=room.landlordCards
      player.value.sx=room.players[i].sx
      console.log(pais.value)


      break; // 找到后退出循环
      }
    } 
    for (let i = 0; i < 3; i++) {
      if(room.players[j].id>=room.players[i].id){
        j=i;
      }
    }
      console.log("------------------------------------")
      console.log(player.value.id)
      console.log(j)
      console.log(room.players[j].id)
      if(player.value.id==room.players[j].id){
      console.log("++++++++++++++++++")
      landlordCardlog.value=true;
      }
      console.log("------------------------------------")
  
  


    // 更新 UI 或存储房间 ID
  } else {
    console.error("失败:", data.error);
    }
}

// 3. 处理不叫地主
function callLandResult(data) {
  landlordCardlog.value=true;


}

// 3. 处理第一次叫地主
function callLandScResult(data) {
  console.log(data)
  player.value.score=1;
  player.value.bid=false
  landlordCardlog.value=false;
  console.log("叫的分数："+player.value.score)

}
// 3. 处理成功叫地主
function callLandSccessResult(data) {
  console.log("叫尼玛呢")
  playlog.value=true 
  pais.value = sortCards( [...pais.value.map(card => ({
    ...card,
    // 保留原有唯一标识（如果已存在）
    uniqueId: card.uniqueId || generateUniqueId(card, 'player')
  })),
  ...landlordCards.value.map((card, index) => ({
    ...card,
    uniqueId: generateUniqueId(card, 'landlord', index)
  }))] )

;

}

// 3. 处理成功收到牌
function shoupaiResult(data) {
  console.log(data)
  playlog.value=true
  upCard.value = JSON.parse(data); 
  selectedCard.value=[]
  console.log(upCard.value)

}   

// 3. 处理成功收到牌
function guangbo(data) {
  console.log(data)
  upCard.value = JSON.parse(data); 
  console.log("广播者顺序==="+upCard.value.sx)

  console.log("自己顺序=="+player.value.sx)

  const broadcasterSx = upCard.value.sx; // 广播者顺序
  const currentSx = player.value.sx;          // 自己顺序
  console.log("广播者顺序"+broadcasterSx)

  console.log("自己顺序"+currentSx)
  console.log(upCard.value.handCards)
    // 计算左右邻居（环形逻辑）
    const calculateNeighbors = (current) => ({
    left: current === 1 ? 3 : current - 1,
    right: current === 3 ? 1 : current + 1
  });

  const { left, right } = calculateNeighbors(currentSx);

    // 判断目标容器
    let targetContainer;
  if (broadcasterSx === left) {
    targetContainer = 'left';
  } else if (broadcasterSx === right) {
    targetContainer = 'right';
  } else {

    console.log("第一个")
    return;
  }

    // 更新对应容器（示例使用数组存储，可替换为DOM操作）
    if (targetContainer === 'left') {
    leftContainer.value =  upCard.value.handCards;
  } else {
    rightContainer.value = upCard.value.handCards;
  }
  upCard.value=null;
  console.log(pais.value);
  console.log(leftContainer.value);
  console.log(rightContainer.value);

}

   onMounted(()=>{
    ws =new WebSocket('ws://localhost:8080/chart/'+player.value.id);
    initWebSocketMessenger(ws)
    ws.onmessage = (event) => {
  try {
    // 解析后端返回的 JSON 字符串
    const response = JSON.parse(event.data);
    console.log(response.type)
    // 根据消息类型处理不同逻辑
    switch (response.type) {
      case "creatroom":
        console.log(response.data)
        handleCreateRoomResult(response.data);
        break;
      case "joinroom":
        handleStartGameResult(response.data);
        break;
      case "inits":
      initsResult(response.data);
      break;
      case "shou pai":
      shoupaiResult(response.data)
      break;
      case "calland":
      callLandResult(response.data)
      break;
      case "call score":
      callLandScResult(response.data)
      break;
      case "guan bo pai":
      guangbo(response.data)
      break; 
      case "calland sccess":
      callLandSccessResult(response.data)
      break;
      case "readlly":
      landlordCardlog2.value=true
      break;
      case "error":
      handleStarterroeResult(response.data);
        break;
      default:
        console.warn("未知消息类型:", response.type);
    }
  
  
  
  
  } catch (error) {
    console.error("解析 WebSocket 消息失败:", error);
  }
};

   })

  
  
  
  </script>
  
  <style lang="scss" scoped>
  .disable-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 20%;
    height: 100%;
    background: rgba(10, 10, 10, 0.5); /* 半透明灰色 */
    border-radius: 30%;
    z-index: 1; /* 确保覆盖在文字层上方 */
    pointer-events: none; /* 允许点击穿透到下层（如果需要） */
  }
  
      /* 全屏边框容器 */
      .full-screen-border1 {
        display: flex;            /* 启用 Flex 布局 */
        flex-direction: column;
        width: 100vw;             /* 视口宽度 */
        height: 100vh;            /* 视口高度 */
        //border: 3px solid black; /* 边框样式 */

        
  
              /* 背景图设置 */
        background-image: url('src/assets/zuo.jpg'); /* 替换为你的图片路径 */
        background-size: cover; /* 覆盖整个容器 */
        background-position: center; /* 居中显示 */
        background-repeat: no-repeat; /* 禁止重复 */

        .miden{
          display: flex;            /* 启用 Flex 布局 */
          width: 100vw;             /* 视口宽度 */
          height: 70vh;            /* 视口高度 */
          //border: 3px solid black; /* 边框样式 */
          .content {
            width: 100%;          /* 继承外层容器的100%宽度 */
            height: 100%;         /* 继承外层容器的100%高度 */
            //border: 2px solid pink; /* 与外层容器相同的边框 */
            justify-content: center; /* 水平居中 */
            align-items: center;    /* 垂直居中 */
            text-align: center; 
            position: relative;
            .shoupai1{
              width: 40%;          /* 继承外层容器的100%宽度 */
              height: 20%; 
              position: absolute;   /* 绝对定位 */
              top: 0;           /* 贴紧父容器底部 */
              left: 0;  
              //border: 3px solid black; /* 边框样式 */
              display: flex;            /* 启用 Flex 布局 */
              justify-content: center;  /* 垂直居中内容 */
            }
            .shoupai2{
              width: 40%;          /* 继承外层容器的100%宽度 */
              height: 20%; 
              position: absolute;   /* 绝对定位 */
              top: 0%;           /* 贴紧父容器底部 */
              right: 0;  
              //border: 3px solid rgb(8, 5, 5); /* 边框样式 */
              display: flex;            /* 启用 Flex 布局 */
              justify-content: center;  /* 垂直居中内容 */
            }

            .chupai {
              width: 100%;          /* 继承外层容器的100%宽度 */
              height: 20%; 
              
              //border: 3px solid black; /* 边框样式 */
              display: flex;            /* 启用 Flex 布局 */
              justify-content: center;  /* 垂直居中内容 */
                /* 新增定位逻辑 */
              position: absolute;   /* 绝对定位 */
              bottom: 0;            /* 贴紧父容器底部 */
              left: 0;  
            }
            
            .image-wrapper {
              width: 70%;
              height: auto;
              position: absolute;
              left: 30%;         /*水平居中*/
              top: 60%;       /*垂直居中*/
            }
            .image-wrapper2 {
              width: 70%;
              height: auto;
              position: absolute;
              right: -25%;         /*水平居中*/
              top: 60%;       /*垂直居中*/
            }
          }
        }

      } 
      
  
      .top{
        display: flex;            /* 启用 Flex 布局 */
        justify-content: center;  /* 垂直居中内容 */
        width: 100vw;             /* 视口宽度 */
        height: 10vh;            /* 视口高度 */
        //border: 3px solid black; /* 边框样式 */

        
      }
  
      .left{
        display: flex;            /* 启用 Flex 布局 */
        width: 13vw;             /* 视口宽度 */
        height:70%;            /* 视口高度 */
        //border: 3px solid black; /* 边框样式 */
        flex-direction: column;  /* 设置垂直方向排列 */
        gap: 10px;               /* 可选：子元素间距 */
        /* 可选高度约束 */
        
      }
      .right{
        display: flex;            /* 启用 Flex 布局 */
        justify-content: center;  /* 垂直居中内容 */
        width: 13vw;             /* 视口宽度 */
        height: 70%;            /* 视口高度 */
        //border: 3px solid black; /* 边框样式 */
        flex-direction: column;  /* 设置垂直方向排列 */
        
      }
        .down{
        display: flex;            /* 启用 Flex 布局 */
        justify-content: center;  /* 垂直居中内容 */
        width: 100vw;             /* 视口宽度 */
        height: 20vh;            /* 视口高度 */
        //border: 3px solid black; /* 边框样式 */
        
      }

      .down .pais{
        width: 100%;
        height: 100%;
        //background-color: pink;
      }
          /* 内部内容区域 */
      


      
      
      .btn-image {
        display: block;
        width: 20%; /* 根据实际图片尺寸调整 */
        height: auto;
      }
      
      .art-text {
        position: absolute;
        bottom: 25%; /* 文字垂直位置 */
        width: 20%;          /* 继承外层容器的100%宽度 */
        height: 70%;         /* 继承外层容器的100%高度 */
        font-size: calc(3vw); /* 与容器同缩放比例 */

        
        /* 艺术字样式 */
        font-family: 'Arial Black', cursive;
        text-transform: uppercase;
        color: #efeee9;
        text-shadow: 
          2px 2px 4px rgb(255, 255, 255),
          0 0 10px rgb(236, 234, 223);
        
        /* 渐变文字效果 */
        background: linear-gradient(45deg, #f6f3f3, #faf8f7);
        -webkit-background-clip: text;
        background-clip: text;
        color: transparent;
        
        /* 3D 浮雕效果 */
        filter: drop-shadow(2px 2px 2px rgba(0,0,0,0.3));
      }


      // SCSS样式
.win-dialog {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 2rem;
  border-radius: 1rem;
  background: gold;
  box-shadow: 0 0 20px rgba(255,215,0,0.5);
  text-align: center;
  border: solid 2px rgba(255, 215, 0, 0.5);
  
  h2 {
    font-size: 2.5rem;
    margin: 0 0 1rem;
  }
  
  button {
    padding: 0.5rem 2rem;
    background: green;
    border: none;
    border-radius: 5px;
    cursor: pointer;
  }
}


/* 主内容模糊效果 */
.blur-background {
  filter: blur(5px);
  opacity: 0.6;
  transition: all 1s ease;
  pointer-events: none; /* 防止点击主内容 */
}
/* 胜利弹窗样式 */
.win-dialog {
  background: white;
  padding: 2rem;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  animation: pop 0.5s;
}
/* 胜利弹窗样式 */
.win-dialog {
  background: white;
  padding: 2rem;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
  animation: pop 0.5s;
}
  </style>